<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');
/**
 * @param mprogram $mprogram
 * 
 *
 */
class uindex extends CI_Controller {

    var $theme_data = array(
        'layout_main' => 'frontend/layout/home',
        'left' => 'frontend/include/left',
        'right' => 'frontend/include/right',
    );

    function __construct() {
        parent::__construct();
		$this->load->helper('module');
		$this->load->model('mcategory');
		$this->load->model('mgame');
		$this->load->model('muser');
		$this->load->model('mmodules');
		$this->load->model('mgamecategory');
		$this->scache->html();
    }

    public function index($page = 0) {
		//load_modules();
        $data = array();
		
		if($this->input->get('act') && $this->input->get('do') ){
			return $this->gamescore($this->input->get('act'), $this->input->get('do'));
		}
	
		$data['seo'] = $this->sseo->get('trang-chu');
        $this->theme_data["main"] = "frontend/uindex/home";
        $this->template->view($this->theme_data, $data);
    }
	
	public function play($game_code = '') {
		 $data = array();
		 $this->load->model("mgameinstruction");
		 $this->load->model("madmin");
        if ($game_code == '')
		redirect(page404(), 301);
        $game_id = explode("-", $game_code);
        $game_id = end($game_id);
        
        if (!$game_id || $game_id <= 0)
			redirect(page404(), 301);
		
		$data['game'] = $this->mgame->get($game_id);
		if (!$data['game'])
			redirect(page404(), 301);
		if($data['game']->game_status <1 && !$this->madmin->checkLogin())
			redirect(page404(), 301);
		$data['cate'] = $this->mgamecategory->get($game_id,'game_id');
		if($data['cate']) $data['cate'] = $this->mcategory->get($data['cate']->cat_id);
		if ($data['cate'] && $data['cate']->cat_parent != 0) {
			$data['parent_cate'] = $this->mcategory->get($data['cate']->cat_parent);
		}
		
		$this->msystem->set_global('game_id',$game_id);
		$this->msystem->set_global('cat_id',(array)@$data['cate']->cat_id);
		
		//lưu điểm
		if($game_id == @$this->session->userdata('game_id')){
			$this->gamescore(@$this->session->userdata('game_key'),@$this->session->userdata('game_score'));
			
		}
		$data['msg'] = '';
		if($this->session->flashdata('game_score'))
			$data['msg'] = $this->session->flashdata('game_score');
		$this->mgame->update_view($game_id);
		
		$data['instructions'] = $this->mgameinstruction->gets($game_id,'game_id');
		$data['seo'] = $this->sseo->set($data['game']);
		$data['canonical'] = game_url($data['game']->game_id, $data['game']->game_code);
		$data['og_image'] = image_thumbnail($data['game']->game_thumb, 'thumbnail');
		$this->theme_data['layout_main'] = 'frontend/layout/playgame';
		$this->theme_data["main"] = "frontend/uindex/play";
        $this->template->view($this->theme_data, $data);
	}
	
	public function category($cate_code, $page  = 1, $ordering = '') {
		$data = array();
        $data['cate'] = $this->mcategory->get($cate_code, 'cat_code');
		if (!$data['cate'] ) {
			redirect(page404(), 301); 
		}
		if ($data['cate']->cat_parent != '0') {
			return $this->category_child( $data['cate'], $page, $ordering);
		}
		$this->db->order_by('cat_order asc');
		$data['subcates'] = $this->mcategory->gets(array('cat_parent' => $data['cate']->cat_id));
		
		$data['seo'] = $this->sseo->set($data['cate']);
		$this->msystem->set_global('cat_id',(array)@$data['cate']->cat_id);
		$this->theme_data['layout_main'] = 'frontend/layout/parentcate';
		$this->theme_data['main'] = 'frontend/uindex/category';
        $this->template->view($this->theme_data, $data);
	}
	
	function category_child($cate_code, $page = 1, $ordering = '') {
		$data = array();
		if (is_object($cate_code)) {
			$data['cate'] = $cate_code;
		}else {
			 $data['cate'] = $this->mcategory->get($cate_code, 'cat_code');
		}
		if (!$data['cate']) {
			redirect(page404(), 301); 
		}
		if ($data['cate'] && $data['cate']->cat_parent != 0) {
			$data['parent_cate'] = $this->mcategory->get($data['cate']->cat_parent);
		}
		$this->msystem->set_global('cat_id',(array)@$data['cate']->cat_id);
		$page = ($page <= 0) ? 1 : $page;
        $config = array();
        $config['per_page'] = 54;
        $config['cur_page'] = $page;
        $config['base_url'] = base_url($data['cate']->cat_code);
		
		$this->db->where('game_status > ',0);
		$total = $this->mgame->get_by_cate($data['cate']->cat_id);
        $config['total_rows'] =count($total);
        $this->pagination->initialize($config);
		
		$this->db->limit($config['per_page'], ($config['cur_page'] - 1) * $config['per_page']);
		$this->db->where('game_status > ',0);
		switch ($ordering) {
			case 'newest' : 
			$this->db->order_by('game.game_id desc');
			break;
			
			case 'topview' :
			$data['topview'] = 1;
			$this->db->order_by('game_view desc');
			break;
		}
		$data['games'] =  $this->mgame->get_by_cate($data['cate']->cat_id);
		
		$this->theme_data['layout_main'] = 'frontend/layout/subcate';
		$this->theme_data['main'] = 'frontend/uindex/category_child';
		$this->template->view($this->theme_data, $data);
	}
	
	function search($key_code = '',$page = 0){
		$data = array();
		
		$keyword = $this->input->get_post('search', TRUE);
		$this->load->model('msearch');

		if($keyword =='' && $key_code =='')
			redirect(page404(), 301);
		
		if($key_code !=''){
			$search = $this->msearch->get($key_code,'search_code');
		}
		else {
			$this->db->where('search_keyword',$keyword);
			$search = $this->msearch->get();
			//$search = $this->db->query("SELECT * FROM (`search`) WHERE `search_keyword` = ".$this->db->escape($keyword)." COLLATE utf8_bin")->first_row();  
			//$search = $this->db->query("SELECT * FROM (`search`) WHERE `search_keyword` = ".$this->db->escape($keyword)." COLLATE utf8_bin")->first_row();  
		}
		if($search){
			if($key_code == '') {
				redirect(base_url().'tim-kiem/'.$search->search_code.'.html', 301);
			}
			else {
				$data['title'] = 'Kết quả tìm game: '.$search->search_keyword;
				$page = ($page <= 0) ? 1 : $page;
				$game_data = json_decode($search->search_cache);
				$config = array();
				$config['per_page'] = 54;
				$config['cur_page'] = $page;
				$config['base_url'] = base_url().'tim-kiem/'.$search->search_code.'';
				$config['total_rows'] =count($game_data);
				$this->pagination->initialize($config);
				$data['games'] =  $this->msearch->pagination_json($game_data,$config);
				$this->msearch->update_view($search->search_id);
				$this->theme_data['layout_main'] = 'frontend/layout/home';
				$this->theme_data['main'] = 'frontend/uindex/game_list';
				$this->template->view($this->theme_data, $data);
			}
		}
		else{
			$arr_insert = array();
			$arr_insert['search_code'] = $this->sseo->seolink($keyword);
			$this->db->select('game_id,game_title,game_code,game_thumb, game_view, game_content');
			$this->db->like('game_title',$keyword);
			$this->db->or_like('game_code',$arr_insert['search_code']);
			$game = $this->mgame->gets(0,'game_status >');
		
			//$game = $this->db->query("SELECT * FROM (`game`) WHERE `game_title` like ".$this->db->escape($keyword)." COLLATE utf8_bin")->first_row();  
			
			
			for($i=1; $i<200; $i++){
				$check = $this->msearch->get($arr_insert['search_code'],'search_code');
				if($check) $arr_insert['search_code'] = $arr_insert['search_code'].'.'.$i;
				else break;
			}
			$arr_insert['search_keyword'] = trim($keyword);
			$arr_insert['search_cache'] = json_encode($game);
			$this->msearch->insert($arr_insert);
			redirect(base_url().'tim-kiem/'.$arr_insert['search_code'].'.html', 301);
		}
		
	}
	
	function page404(){
		$data = array();
		$this->output->set_status_header('404');
		set_status_header(404);
		
		$data['position'] = 'page404';
		$this->theme_data["left"] = null;
		$this->theme_data["right"] = null;
		$this->theme_data["main"] = "frontend/include/page404";
        $this->template->view($this->theme_data, $data);
	}
	function info_detail($info_code = ''){
		$data = array();
		if ($info_code == '')
		redirect(page404(), 301);
		$this->load->model('minfo');
        $info_id = explode("-", $info_code);
        $info_id = end($info_id);
        
        if (!$info_id || $info_id <= 0)
		redirect(page404(), 301);
		
		$data['info'] = $this->mgame->get($info_id);
		if (!$data['info'])
		redirect(page404(), 301);
		
		$this->theme_data["main"] = "frontend/uindex/info";
        $this->template->view($this->theme_data, $data);
		
	}
	//lưu điểm game
	function gamescore($game_key = '', $game_score = 0){
		$this->load->library('user_agent');
		$this->load->model("mgamescore");
		$this->load->model("mgamescores");
		$this->load->model("mloggamescores");
		$this->load->model("muser");
		$this->load->model("madmin");
		$this->load->model("mgame");
		
		$score = intval($this->input->post("gscore"));
		$key = @$this->input->post("gname");
		if(!$key && !$score&& $game_key!='' && $game_score !=0){
			$key = $game_key;
			$score = $game_score;
			$array_items = array('game_key' => '', 'game_id' => '', 'game_score' => '', 'game_referrer' => '');
			$this->session->unset_userdata($array_items);
		}
		$arr_log = array();
		$referrer_link = base_url();
		$arr_log['game_id'] = 0;
		if ($this->agent->is_referral())
		{
			$arr_log['game_id'] = str_replace(".html","",end(explode("-",$this->agent->referrer())));
			$arr_log['log_gscores_referrer'] = $this->agent->referrer();
			$arr_log['game_id'] = intval($arr_log['game_id']);
			$referrer_link = $this->agent->referrer();
		}
		
		//tự động update gkey
		if($arr_log['game_id'] && $arr_log['game_id'] >0){
			if($this->mgame->permission('process_game') || $this->mgame->permission('post_game') || $this->mgame->permission('test_game')) {
				$this->mgame->update($arr_log['game_id'],'game_id',array(
				'game_key'=>$key,
				));
				$this->session->set_flashdata('game_score', 'Update gkey = '.$key.' thành công.');
				redirect($referrer_link, 301);
			}
		}
		
		if(!$this->muser->checkLogin())
		{
			$this->session->set_userdata(array(
							'game_key'=>$key,
							'game_id'=>@$arr_log['game_id'],
							'game_score'=>$score,
							'game_referrer'=>$referrer_link,
							
							));
			
			redirect(user_url('login'), 301);
		}
		/*
		if(!isset($key) || !$key || $key =='' || !$this->muser->use_id || $this->muser->use_id <=0)
		{
			redirect($referrer_link, 301); 
		}
		*/
		$arr_log['log_gscores_ip'] =$this->input->ip_address();
		$arr_log['log_gscores_browser'] =$this->agent->browser();
		$arr_log['log_gscores_platform'] =$this->agent->platform();
		$arr_log['log_gscores_agent'] =$this->agent->agent_string();
		$arr_log['use_id'] = $this->muser->use_id;
		$arr_log['log_gscores_time'] = time();
		$arr_log['log_gscores_game_key'] = $key;
		
		if(!$score || !$key || $score <=0)
		{
			if(!$score)
				$arr_log['log_gscores_code'] ='score_null';
			if(!$key)
				$arr_log['log_gscores_code'] ='key_null';
			if(!$score <=0)
				$arr_log['log_gscores_code'] ='score_less_0';
			$this->mloggamescores->insert($arr_log);
			redirect($referrer_link, 301); 
		}
		//$game = $this->mgame->get($key, 'game_key');
		$game = $this->mgame->get($arr_log['game_id'], 'game_id');
		
		if(!$game) {
			$arr_log['log_gscores_code'] ='game_not_exist';
			$this->mloggamescores->insert($arr_log);
			redirect($referrer_link, 301);
		}

		//insert diem to log
		$arr_insert= array();
		$arr_insert['game_id'] = $game->game_id;
		$arr_insert['use_id'] = $this->muser->use_id;
		$arr_insert['gscore_scores'] = $score;
		$arr_insert['gscore_time_create'] = time();
		$arr_insert['gscore_time_update'] = time();
		$arr_insert['gscore_ip'] =  $this->input->ip_address();
		$this->mgamescores->insert($arr_insert);
		//update diem
		$check = $this->mgamescore->get(array(	'game_id'=>$game->game_id,
												'use_id'=>$this->muser->use_id));
		if(!$check){
			$arr_insert['gscore_score'] = $score;
			$this->mgamescore->insert($arr_insert);
		}
		else {
			$arr_update= array();
			$arr_update['gscore_score'] = $score;
			$arr_update['gscore_time_update'] = time();
			$arr_update['gscore_ip'] = $this->input->ip_address();
			$this->db->where('use_id',$this->muser->use_id);
			$this->mgamescore->update($game->game_id, 'game_id',$arr_update);
		}
		if($game->game_key == ''){
			$this->mgame->update($arr_log['game_id'],'game_id',array(
				'game_key'=>$key,
			));
			
		}
		$this->session->set_flashdata('game_score', 'Lưu điểm thành công');
		redirect(game_url($game->game_id,$game->game_code), 301); 
	}
}
